package com.yunfei.yikao.web.controlller;

import com.yunfei.yikao.web.dao.ZhangyunfeiYikaoMapper;
import com.yunfei.yikao.web.dataobject.ZhangyunfeiYikao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.validation.Valid;
import java.util.List;

/**
 * @Author: yunfei
 * @Date: 17:14
 */
@Controller
public class UsersControl {
    @Autowired
    ZhangyunfeiYikaoMapper yikaoMapper;

    @RequestMapping(path = "/users")
    public ModelAndView query() {
        ModelAndView view = new ModelAndView();
        List<ZhangyunfeiYikao> userList = yikaoMapper.selectAll();
        view.addObject("users", userList);
        view.setViewName("users");
        return view;
    }

    @RequestMapping(path = "/signup")
    public ModelAndView toSignup(@ModelAttribute("userForm") ZhangyunfeiYikao yikao,
                                 Model model) {
        ModelAndView view = new ModelAndView();
        view.setViewName("signup");
        view.addObject(BindingResult.class.getName() + ".userForm",
                model.asMap().get("userFormError"));
        return view;
    }

    @RequestMapping(path = "/user/signup")
    public RedirectView signup(@Valid ZhangyunfeiYikao yikao, BindingResult result,
                               RedirectAttributes attributes) {
        RedirectView view = new RedirectView();
        if (result.hasErrors()) {
//            返回注册页面，保留输入信息
            attributes.addFlashAttribute("userForm", yikao);
            attributes.addFlashAttribute("userFormError", result);

            view.setUrl("/signup");
        } else {
            yikaoMapper.insert(yikao);
            view.setUrl("/users");
        }
        return view;

    }


}

